﻿using Unity.Collections;

/// <summary>
/// 仅允许单次引用双向链表
/// </summary>
public struct EntityLinkedSetList
{
    public GpuHudEntityBase head;
    public GpuHudEntityBase tail;
    public int Count;
    private NativeHashMap<int,bool> alreadExist;

    public static EntityLinkedSetList GetList()
    {
        EntityLinkedSetList list = new EntityLinkedSetList();
        list.Count = 0;
        list.alreadExist = new NativeHashMap<int, bool>(50, Allocator.Persistent);
        return list;
    }
    
    public void AddLast(GpuHudEntityBase node)
    {
        if (alreadExist.ContainsKey(node.GetHashCode()))
        {
            return;
        }
        alreadExist.Add(node.GetHashCode(), true);
        if (head == null)
        {
            head = node;
            tail = node;
        }
        else
        {
            node.preEntity = tail;
            tail.nextEntity = node;
            tail = node;
        }
        Count++;
    }

    public void Remove(GpuHudEntityBase node)
    {
        if (node == null) return;
        if (!alreadExist.ContainsKey(node.GetHashCode()))
        {
            return;
        }
        alreadExist.Remove(node.GetHashCode());
        if (node.preEntity != null)
        {
            if (tail == node)
            {
                tail = node.preEntity;
            }
            else
            {
                node.nextEntity.preEntity = node.preEntity;
                node.preEntity.nextEntity = node.nextEntity;
            }
        }
        else
        {
            //preEntity==null,是第一个节点,如果Count = 1,则Tail也是node,否则,就是移除第一个节点
            if (Count == 1)
            {
                head = null;
                tail = null;
            }
            else
            {
                head = node.nextEntity;
                head.preEntity = null;
            }
        }
        node.preEntity = null;
        node.nextEntity = null;
        Count--;
    }


    public void Dispose()
    {
        if (alreadExist.IsCreated)
        {
            alreadExist.Dispose();
        }
    }

    public void Clear()
    {
        head = null;
        tail = null;
        Count = 0;
        if (alreadExist.IsCreated)
        {
            alreadExist.Clear();
        }
    }
}
